package vip.xiaonuo.common.util;

import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import vip.xiaonuo.common.exception.CommonException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;

/**
 * @author zjt
 * @description
 * @date 2025/7/16 11:28
 */
public class CommonXmlUtil extends XmlUtil {

    /**
     * 将XML字符串转换为Java对象
     *
     * @param xmlStr    XML字符串
     * @param beanClass 目标对象类型
     * @return 转换后的Java对象
     */
    public static <T> T xmlToBean(String xmlStr, Class<T> beanClass) {
        try {
            // 1. 将字符串转为Document对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
            // 2. 使用Hutool进行转换
            return xmlToBean(doc.getDocumentElement(), beanClass);
        } catch (Exception e) {
            throw new CommonException("XML转换失败", e);
        }
    }
}
